<template>
  <div class="template-preview">
    <div class="template-header">
      <div class="template-info">
        <h3>{{ template.templateName }}</h3>
        <div class="template-meta">
          <span class="template-id">模板ID: {{ template.templateId }}</span>
          <el-tag :type="template.enableStatus === 1 ? 'success' : 'danger'">
            {{ template.enableStatus === 1 ? "已启用" : "未启用" }}
          </el-tag>
          <el-tag :type="getProjectTypeColor(template.projectType)">
            {{ template.projectType || '未分类' }}
          </el-tag>
        </div>
      </div>
      <div class="template-stats">
        <div><i class="el-icon-folder-opened"></i> 科目总数: {{ totalSubjects }}</div>
        <div><i class="el-icon-edit"></i> 可编辑项: {{ editableCount }}</div>
        <div><i class="el-icon-collection"></i> 汇总项: {{ summaryCount }}</div>
      </div>
    </div>

    <div class="structure-title">
      <i class="el-icon-s-grid"></i> 预算科目结构
    </div>

    <el-table
      :data="subjectTree"
      row-key="subjectId"
      :indent="30"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      border
      default-expand-all
      size="small"
      style="width: 100%"
      class="preview-table"
    >
      <el-table-column prop="subjectName" label="预算科目名称" min-width="260">
        <template #default="{ row }">
          <div class="subject-name" :style="{ marginLeft: `${(row.subjectLevel - 1) * 24}px` }">
            <div>
              <span class="level-indicator">{{ renderLevelPrefix(row.subjectLevel, row.sortOrder) }}</span>
              {{ row.subjectName }}
            </div>
            <div class="subject-info">
              <el-tag v-if="row.isSummary" size="mini" type="info">汇总项</el-tag>
              <el-tag v-if="row.editable" size="mini" type="success">可编辑</el-tag>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="层级" width="100" align="center">
        <template #default="{ row }">
          {{ ['一级', '二级', '三级', '四级', '五级'][row.subjectLevel - 1] || `第${row.subjectLevel}级` }}
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: "TemplatePreview",
  props: {
    template: {
      type: Object,
      required: true
    }
  },
  computed: {
    // 将科目列表转换为树形结构
    subjectTree() {
      if (!this.template?.sciBudgetSubjectList) return [];

      const list = [...this.template.sciBudgetSubjectList];
      const map = {};
      const roots = [];

      // 创建映射关系
      list.forEach(item => {
        map[item.subjectId] = {
          ...item,
          children: []
        };
      });

      // 构建树形结构
      list.forEach(item => {
        const parentId = item.parentId;
        if (parentId === "0" || !map[parentId]) {
          roots.push(map[item.subjectId]);
        } else {
          map[parentId].children.push(map[item.subjectId]);
        }
      });

      // 按sortOrder排序子节点
      const sortChildren = (node) => {
        if (node.children && node.children.length) {
          node.children.sort((a, b) => a.sortOrder - b.sortOrder);
          node.children.forEach(sortChildren);
        }
      };

      roots.forEach(sortChildren);
      return roots.sort((a, b) => a.sortOrder - b.sortOrder);
    },

    // 统计科目总数
    totalSubjects() {
      return this.template?.sciBudgetSubjectList?.length || 0;
    },

    // 统计可编辑科目数量
    editableCount() {
      return this.template?.sciBudgetSubjectList?.filter(item => item.editable).length || 0;
    },

    // 统计汇总科目数量
    summaryCount() {
      return this.template?.sciBudgetSubjectList?.filter(item => item.isSummary).length || 0;
    }
  },
  methods: {
    getProjectTypeColor(type) {
      const colors = {
        '纵向': 'primary',
        '横向': 'warning',
        '其他': 'info'
      };
      return colors[type] || 'info';
    },

    // 生成层级前缀 (如 "一、", "(一)", "1.")
    renderLevelPrefix(level, order) {
      const prefixes = [
        ['一', '二', '三', '四', '五'],
        ['(一)', '(二)', '(三)', '(四)', '(五)'],
        ['1.', '2.', '3.', '4.', '5.'],
        ['(1)', '(2)', '(3)', '(4)', '(5)'],
        ['①', '②', '③', '④', '⑤']
      ];

      // 使用对应的层级前缀
      const prefixSet = prefixes[level - 1] || [];
      // 如果没有对应的前缀，直接返回原始索引+1
      return prefixSet[order - 1] || `${order}.`;
    }
  }
};
</script>

<style scoped>
.template-preview {
  padding: 15px;
  height: 100%;
  box-sizing: border-box;
}

.template-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  padding: 15px;
  background: #f9fafc;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.template-info h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #333;
}

.template-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
}

.template-id {
  color: #666;
}

.template-stats {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  font-size: 13px;
  color: #666;
  min-width: 180px;
}

.template-stats div {
  margin-bottom: 5px;
  display: flex;
  align-items: center;
}

.template-stats i {
  margin-right: 5px;
  font-size: 14px;
}

.structure-title {
  font-size: 16px;
  font-weight: 600;
  margin: 10px 0;
  padding-left: 10px;
  border-left: 4px solid #409eff;
  line-height: 20px;
}

.structure-title i {
  margin-right: 8px;
  color: #409eff;
}

.preview-table {
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.subject-name {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.level-indicator {
  display: inline-block;
  width: 28px;
  color: #909399;
}

.subject-info {
  display: flex;
  gap: 5px;
}

::v-deep .el-table__row {
  cursor: pointer;
}

::v-deep .el-table__row:hover {
  background-color: #f5f7fa;
}
</style>
